package org.pearl.oauth2.authorizationserverdemo.oauth2.sms;

import org.pearl.oauth2.authorizationserverdemo.dao.UserMapper;
import org.pearl.oauth2.authorizationserverdemo.pojo.UserInfoDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by TD on 2021/7/6
 * 自定义加载用户信息接口实现
 */
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    /**
     * @param username 用户名
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 数据库查询用户
        /*User user = userService.getUserByName(username);*/
        UserInfoDO userInfoDO = userMapper.getUserInfoByUserName(username);
        if (userInfoDO == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        List<GrantedAuthority> authorityList =
                AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        User myUser = new User(userInfoDO.getUserName(), userInfoDO.getPassword(), authorityList);
        return myUser;
    }
}
